package com.zhang.util;

import com.alibaba.fastjson.JSON;
import com.zhang.entity.co.MachineResult;
import com.zhang.exception.ServiceException;
import com.zhang.service.AsyncService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * User: 张
 * Date: 2024-11-14
 * Time: 18:44
 * Description:
 */
@Component
public class DeviceOperateUtil {

    @Value("${python.pythonInterpreter}")
    private String pythonInterpreter;
    @Value("${python.pythonPath}")
    private String scriptPath;
    @Value("${operation.correct}")
    private Integer correct;
    Integer exitCode;

    public String DeviceOperate(String method, String action, Map<String, String> parameter) throws Exception {
        String result = "";
        if (method.equalsIgnoreCase("machine")) {
            result = DeviceOperateMachine(action, parameter);
        }
        if (method.equalsIgnoreCase("system")){
            result = DeviceOperateSystem(action, parameter);
        }
        return result;
    }


    public String DeviceOperateMachine(String action, Map<String, String> parameter) throws Exception {
        StringBuffer stringBuffer = new StringBuffer();
        exitCode = null;
        try {
            List<String> list = new ArrayList<>();
            list.add(pythonInterpreter);
            list.add(scriptPath);
            list.add(action);
            if (parameter != null && (!parameter.isEmpty())){
                for (String key : parameter.keySet()) {
                    list.add(key);
                    list.add(parameter.get(key));
                }
            }
            ProcessBuilder pb = new ProcessBuilder(list);
            Process process = pb.start();
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
            String line = "";
            while ((line = reader.readLine()) != null) {
                stringBuffer.append(line);
            }
            exitCode = process.waitFor();
            process.destroy();
            pb.directory();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (exitCode == null || !exitCode.equals(correct)) {
            throw new Exception("python脚本运行异常");
        }
        if (!stringBuffer.toString().equalsIgnoreCase("Ture")) {
            throw new Exception(stringBuffer.toString());
        }
        String result = stringBuffer.toString();
        stringBuffer.delete(0, stringBuffer.length());
        // todo 源代码与plc连接有问题,导致反复连接，出现多条json 返回，获取最后一个
        result = reduceJson(result);
        return result;
    }

    private String DeviceOperateSystem(String action, Map<String, String> parameter) {
        if (action.equals("sleep")){
            try {
                Thread.sleep(Integer.parseInt(parameter.get(action)));
            }catch (Exception e){
                throw new ServiceException("参数异常");
            }
        }
        if (action.equalsIgnoreCase(parameter.get("stop"))) AsyncService.flag = 1;
        return JSON.toJSONString(new MachineResult(200, "ok"));
    }
    private String reduceJson(String JsonStr){
        String[] split = JsonStr.split("-*-");
        return split[split.length - 1];
    }
}
